#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "driver/mcpwm.h"


void app_main(void)
{
    uint32_t duty_in_us = 0;
    mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0A, SERVO_PULSE_GPIO); 
    mcpwm_gpio_init(MCPWM_UNIT_1, MCPWM0A, 17); 

    mcpwm_config_t pwm_config = {
        .frequency = 500*1000,
        .cmpr_a = 50,       
        .counter_mode = MCPWM_UP_COUNTER,
        .duty_mode = MCPWM_DUTY_MODE_0,
    };
    mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_0, &pwm_config);
    mcpwm_set_duty(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_A, 60);
    
    // pwm_config.frequency = 10000;
    // mcpwm_init(MCPWM_UNIT_1, MCPWM_TIMER_0, &pwm_config);
    // mcpwm_set_duty(MCPWM_UNIT_1, MCPWM_TIMER_0, MCPWM_OPR_A, 20);

    //对于 ESP32S3 芯片来说
    //由此看出，同一个unit，同一个定时器，不能输出不同的频率，可以根据 MCPWM_OPR_"X"  不同的X可以产生不同的占空比
    //不同的unit，同一个定时器可以输出不同的频率,与MCPWM_OPR_"X" 无关。
    //理论上能生成 6个不同频率的PWM信号
    //12个不同占空比的PWM信号(其中同一个unit 同一个timer 生成的频率 相同)
    //无法产生1Mhz的PWM信号，可以产生 1Mhz 被 x 整除的信号。
    //最小可变元 为 1us 

    //  根据文件 mcpwm.h 中的 mcpwm_io_signals_t 结构体可得
    //一个 unit 可以产生6个PWM信号，3个输入捕获，3个同步信号，三个错误信号
    // 这些引脚均可编程为 任意 "普通引脚"

    // duty_in_us = mcpwm_get_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_A);
    // printf("duty_in_us = mcpwm_get_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_A) = %d\r\n", duty_in_us);

    ////////////////////////////////////////////
/*
    // MCPWM1A 关注最后的 1A 即为timer1 MCPWM_OPR_A
    mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM1A, 17);               
    pwm_config.frequency = 10000;
    mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_1, &pwm_config); 
    mcpwm_set_duty(MCPWM_UNIT_0, MCPWM_TIMER_1, MCPWM_OPR_A, 40);

*/

    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}
